<template>
  <div class="project-list-container">
    <div class="page-header">
      <h2>项目列表</h2>
      <div>
        <el-button type="primary" @click="showCreateDialog">
          新建项目
        </el-button>
        <el-button type="success" @click="fetchProjects">
          刷新列表
        </el-button>
        <el-button v-if="isAdmin" type="warning" @click="createTestProject">
          创建测试项目
        </el-button>
        <el-button v-if="isAdmin" type="info" @click="checkAllProjects">
          检查数据
        </el-button>
      </div>
    </div>

    <!-- 项目列表 -->
    <el-card v-loading="loading">
      <div v-if="isAdmin" class="debug-info">
        <strong>用户信息：</strong> {{ JSON.stringify(currentUser) }}
      </div>
      
      <el-table :data="projects" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="项目名称" />
        <el-table-column prop="description" label="项目描述" show-overflow-tooltip />
        <el-table-column prop="git_repository_url" label="Git仓库" show-overflow-tooltip />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="small" 
              @click="viewProject(scope.row.id)"
            >
              查看
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="showEditDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="showSettingsDialog(scope.row)"
            >
              设置
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 无数据显示 -->
      <el-empty v-if="projects.length === 0" description="暂无项目，请点击新建按钮创建"></el-empty>
    </el-card>

    <!-- 创建项目对话框 -->
    <el-dialog
      v-model="createDialogVisible"
      title="创建新项目"
      width="500px"
    >
      <el-form 
        ref="createFormRef" 
        :model="createForm" 
        :rules="createRules"
        label-width="100px"
      >
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="createForm.name" placeholder="请输入项目名称"></el-input>
        </el-form-item>
        <el-form-item label="项目描述" prop="description">
          <el-input 
            v-model="createForm.description" 
            type="textarea" 
            rows="4"
            placeholder="请输入项目描述"
          ></el-input>
        </el-form-item>
        
        <el-divider content-position="left">Git仓库信息</el-divider>
        
        <el-form-item label="仓库地址" prop="git_repository_url">
          <el-input v-model="createForm.git_repository_url" placeholder="例如: https://github.com/username/repo.git"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="git_username">
          <el-input v-model="createForm.git_username" placeholder="Git用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="git_password">
          <el-input type="password" v-model="createForm.git_password" placeholder="Git密码或访问令牌"></el-input>
          <div class="form-tip">密码会被安全存储，用于AI自动操作Git仓库</div>
        </el-form-item>
        <el-form-item label="分支" prop="git_branch">
          <el-input v-model="createForm.git_branch" placeholder="Git分支，默认为main"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreateForm" :loading="submitting">
          确认
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑项目对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑项目"
      width="600px"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="120px"
      >
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="项目描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="Git仓库地址" prop="git_repository_url">
          <el-input v-model="editForm.git_repository_url" />
        </el-form-item>
        <el-form-item label="Git用户名" prop="git_username">
          <el-input v-model="editForm.git_username" />
        </el-form-item>
        <el-form-item label="Git分支" prop="git_branch">
          <el-input v-model="editForm.git_branch" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm" :loading="submitting">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 项目设置对话框 -->
    <el-dialog
      v-model="settingsDialogVisible"
      title="项目设置"
      width="600px"
    >
      <el-form
        ref="settingsFormRef"
        :model="settingsForm"
        :rules="settingsRules"
        label-width="120px"
      >
        <!-- Git仓库设置 -->
        <el-divider content-position="left">Git仓库设置</el-divider>
        <el-form-item label="Git访问令牌" prop="git_access_token">
          <el-input 
            v-model="settingsForm.git_access_token"
            type="password"
            show-password
            placeholder="请输入Gitee私人访问令牌"
          />
          <div class="form-tip">用于自动执行Git操作，请确保有足够的仓库访问权限</div>
        </el-form-item>

        <!-- 数据库设置 -->
        <el-divider content-position="left">数据库设置</el-divider>
        <el-form-item label="数据库类型" prop="db_type">
          <el-select v-model="settingsForm.db_type" placeholder="请选择数据库类型">
            <el-option label="PostgreSQL" value="postgresql" />
            <el-option label="MySQL" value="mysql" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据库主机" prop="db_host">
          <el-input v-model="settingsForm.db_host" placeholder="例如: localhost 或 IP地址"/>
        </el-form-item>
        <el-form-item label="数据库端口" prop="db_port">
          <el-input-number 
            v-model="settingsForm.db_port" 
            :min="1" 
            :max="65535"
            placeholder="PostgreSQL默认5432，MySQL默认3306" 
          />
        </el-form-item>
        <el-form-item label="数据库名称" prop="db_name">
          <el-input v-model="settingsForm.db_name" placeholder="数据库名称"/>
        </el-form-item>
        <el-form-item label="数据库用户名" prop="db_username">
          <el-input v-model="settingsForm.db_username" placeholder="数据库用户名"/>
        </el-form-item>
        <el-form-item label="数据库密码" prop="db_password">
          <el-input 
            v-model="settingsForm.db_password" 
            type="password"
            show-password
            placeholder="数据库密码"
          />
        </el-form-item>
        <el-form-item label="数据库Schema" prop="db_schema">
          <el-input 
            v-model="settingsForm.db_schema" 
            placeholder="PostgreSQL默认为public"
          />
          <div class="form-tip">MySQL可以留空，PostgreSQL默认为public</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="settingsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitSettingsForm" :loading="submitting">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { formatDatetime } from '../../utils/helpers'
import api from '../../api'

export default {
  name: 'ProjectList',
  setup() {
    const store = useStore()
    const router = useRouter()
    const createFormRef = ref(null)
    const editFormRef = ref(null)
    const settingsFormRef = ref(null)
    
    // 获取当前用户信息
    const currentUser = computed(() => store.state.user || {})
    const isAdmin = computed(() => currentUser.value && currentUser.value.role === 'admin')
    
    // 项目列表数据
    const projects = computed(() => store.state.projects || [])
    const loading = computed(() => store.getters.isLoading('projects'))
    
    // 创建项目表单
    const createDialogVisible = ref(false)
    const createForm = ref({
      name: '',
      description: '',
      git_repository_url: '',
      git_username: '',
      git_branch: 'main'
    })

    // 编辑项目表单
    const editDialogVisible = ref(false)
    const editForm = ref({
      id: null,
      name: '',
      description: '',
      git_repository_url: '',
      git_username: '',
      git_branch: 'main'
    })

    // 项目设置表单
    const settingsDialogVisible = ref(false)
    const settingsForm = ref({
      id: null,
      git_access_token: '',
      db_host: '',
      db_port: 5432,
      db_name: '',
      db_username: '',
      db_password: '',
      db_schema: 'public',
      db_type: 'postgresql'
    })

    const createRules = {
      name: [
        { required: true, message: '请输入项目名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      description: [
        { max: 500, message: '长度不能超过 500 个字符', trigger: 'blur' }
      ],
      git_repository_url: [
        { pattern: /^(https?:\/\/|git@).*\.git$/, message: '请输入有效的Git仓库地址', trigger: 'blur' }
      ],
      git_branch: [
        { pattern: /^[a-zA-Z0-9_\-\.\/]+$/, message: '分支名称格式不正确', trigger: 'blur' }
      ]
    }

    const editRules = {
      name: [
        { required: true, message: '请输入项目名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      description: [
        { max: 500, message: '长度不能超过 500 个字符', trigger: 'blur' }
      ],
      git_repository_url: [
        { pattern: /^(https?:\/\/|git@).*\.git$/, message: '请输入有效的Git仓库地址', trigger: 'blur' }
      ],
      git_branch: [
        { pattern: /^[a-zA-Z0-9_\-\.\/]+$/, message: '分支名称格式不正确', trigger: 'blur' }
      ]
    }

    const settingsRules = {
      db_host: [
        { required: true, message: '请输入数据库主机地址', trigger: 'blur' }
      ],
      db_port: [
        { required: true, message: '请输入数据库端口', trigger: 'blur' },
        { type: 'number', min: 1, max: 65535, message: '端口范围为1-65535', trigger: 'blur' }
      ],
      db_name: [
        { required: true, message: '请输入数据库名称', trigger: 'blur' }
      ],
      db_username: [
        { required: true, message: '请输入数据库用户名', trigger: 'blur' }
      ],
      db_password: [
        { required: true, message: '请输入数据库密码', trigger: 'blur' }
      ]
    }

    const submitting = ref(false)
    
    // 获取项目列表
    const fetchProjects = async () => {
      try {
        await store.dispatch('fetchProjects')
        ElMessage.success('项目列表刷新成功')
      } catch (error) {
        console.error('刷新项目列表失败:', error)
        ElMessage.error(`刷新失败: ${error.message || '未知错误'}`)
      }
    }
    
    // 查看项目详情
    const viewProject = (id) => {
      router.push(`/projects/${id}`)
    }
    
    // 显示创建项目对话框
    const showCreateDialog = () => {
      createForm.value = {
        name: '',
        description: '',
        git_repository_url: '',
        git_username: '',
        git_branch: 'main'
      }
      createDialogVisible.value = true
    }

    // 显示编辑项目对话框
    const showEditDialog = (project) => {
      editForm.value = {
        id: project.id,
        name: project.name,
        description: project.description,
        git_repository_url: project.git_repository_url,
        git_username: project.git_username,
        git_branch: project.git_branch
      }
      editDialogVisible.value = true
    }

    // 显示项目设置对话框
    const showSettingsDialog = (project) => {
      settingsForm.value = {
        id: project.id,
        git_access_token: project.git_access_token || '',
        db_host: project.db_host || '',
        db_port: project.db_port || 5432,
        db_name: project.db_name || '',
        db_username: project.db_username || '',
        db_password: project.db_password || '',
        db_schema: project.db_schema || 'public',
        db_type: project.db_type || 'postgresql'
      }
      settingsDialogVisible.value = true
    }
    
    // 提交创建项目表单
    const submitCreateForm = async () => {
      if (!createFormRef.value) return
      
      await createFormRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          try {
            await store.dispatch('createProject', createForm.value)
            ElMessage.success('项目创建成功')
            createDialogVisible.value = false
          } catch (error) {
            ElMessage.error(`创建失败: ${error.message}`)
          } finally {
            submitting.value = false
          }
        }
      })
    }

    // 提交编辑项目表单
    const submitEditForm = async () => {
      if (!editFormRef.value) return
      
      await editFormRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          try {
            await store.dispatch('updateProject', editForm.value)
            ElMessage.success('项目更新成功')
            editDialogVisible.value = false
            fetchProjects()
          } catch (error) {
            ElMessage.error(`更新失败: ${error.message}`)
          } finally {
            submitting.value = false
          }
        }
      })
    }

    // 提交项目设置表单
    const submitSettingsForm = async () => {
      if (!settingsFormRef.value) return
      
      await settingsFormRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          try {
            await store.dispatch('updateProjectSettings', settingsForm.value)
            ElMessage.success('项目设置更新成功')
            settingsDialogVisible.value = false
            fetchProjects()
          } catch (error) {
            ElMessage.error(`更新失败: ${error.message}`)
          } finally {
            submitting.value = false
          }
        }
      })
    }
    
    // 获取状态类型和文本
    const getStatusType = (status) => {
      switch (status) {
        case 'active': return 'success'
        case 'archived': return 'info'
        case 'completed': return 'primary'
        default: return 'info'
      }
    }
    
    const getStatusText = (status) => {
      switch (status) {
        case 'active': return '活跃'
        case 'archived': return '已归档'
        case 'completed': return '已完成'
        default: return status
      }
    }
    
    // 格式化日期
    const formatDate = (date) => {
      if (!date) return '-'
      return formatDatetime(date, 'YYYY-MM-DD HH:mm')
    }
    
    // 创建测试项目
    const createTestProject = async () => {
      if (!isAdmin.value) {
        ElMessage.warning('只有管理员可以创建测试项目')
        return
      }
      
      console.log('正在创建测试项目...')
      try {
        const response = await api.post('/admin/create-test-project')
        console.log('测试项目创建结果:', response.data)
        
        if (response.data && response.data.status === 'success') {
          ElMessage.success('测试项目创建成功')
          fetchProjects()
        } else {
          ElMessage.error(`创建失败: ${response.data?.message || '未知错误'}`)
        }
      } catch (error) {
        console.error('创建测试项目出错:', error)
        ElMessage.error(`创建失败: ${error.message || '未知错误'}`)
      }
    }
    
    // 检查所有项目数据
    const checkAllProjects = async () => {
      if (!isAdmin.value) {
        ElMessage.warning('只有管理员可以检查项目数据')
        return
      }
      
      console.log('正在检查所有项目数据...')
      try {
        const response = await api.get('/admin/check-projects')
        console.log('项目数据检查结果:', response.data)
        
        if (response.data && response.data.status === 'success') {
          const projectData = response.data.data
          console.log('项目总数:', projectData.project_count)
          console.log('所有项目:', projectData.all_projects)
          console.log('所有用户:', projectData.all_users)
          console.log('空owner项目数:', projectData.null_owner_count)
          
          ElMessage.success(`项目检查完成。项目总数: ${projectData.project_count}, 空owner项目数: ${projectData.null_owner_count}`)
        } else {
          ElMessage.error(`检查失败: ${response.data?.message || '未知错误'}`)
        }
      } catch (error) {
        console.error('检查项目数据出错:', error)
        ElMessage.error(`检查失败: ${error.message || '未知错误'}`)
      }
    }
    
    onMounted(() => {
      fetchProjects()
    })
    
    return {
      projects,
      loading,
      createDialogVisible,
      createForm,
      createRules,
      createFormRef,
      editDialogVisible,
      editForm,
      editRules,
      editFormRef,
      settingsDialogVisible,
      settingsForm,
      settingsRules,
      settingsFormRef,
      submitting,
      viewProject,
      showCreateDialog,
      showEditDialog,
      showSettingsDialog,
      submitCreateForm,
      submitEditForm,
      submitSettingsForm,
      getStatusType,
      getStatusText,
      formatDate,
      currentUser,
      isAdmin,
      fetchProjects,
      createTestProject,
      checkAllProjects
    }
  }
}
</script>

<style scoped>
.project-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.debug-info {
  background-color: #f8f8f8;
  padding: 10px;
  margin-bottom: 15px;
  border-radius: 4px;
  font-size: 12px;
  border: 1px dashed #ccc;
  white-space: pre-wrap;
  word-break: break-all;
}

.dialog-footer {
  text-align: right;
  margin-top: 20px;
}
</style> 